package com.glasses.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.glasses.dao.AddressDao;
import com.glasses.entity.Address;
import com.glasses.orm.base.Ex.BaseServiceEx;
import com.glasses.orm.dictionary.IsDefault;
import com.glasses.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ashin on 2018/1/24.
 */
@Service
public class AddressServiceImp extends BaseServiceEx implements AddressService {

    @Autowired
    AddressDao addressDao;

    @Override
    public void init() {
        super.init(addressDao);
    }

    @Transactional
    @Override
    public JSONObject updateDefault(Map map) throws Exception {
        Map addressMap = new HashMap();
        addressMap.put("openId",map.get("openId"));
        addressMap.put("isDefault", String.valueOf(IsDefault.否));
        addressDao.updatep(addressMap);

        Map defaultMap = new HashMap();
        defaultMap.put("id",map.get("id"));
        defaultMap.put("isDefault", String.valueOf(IsDefault.是));
        addressDao.updatep(defaultMap);

        return this.codeMess(sCode,"修改成功");
    }

    @Transactional
    @Override
    public JSONObject addAddress(Map map) throws Exception {
        if(map.get("isDefault").toString().equals(String.valueOf(IsDefault.是))){
            setAllToUnDefault(map);
        }
        return super.insertp(map);
    }

    @Transactional
    @Override
    public JSONObject updateAddress(Map map) throws Exception{
        if(map.get("isDefault").toString().equals(String.valueOf(IsDefault.是))){
            setAllToUnDefault(map);
        }
        return super.updatep(map);
    }

    @Override
    public JSONObject selectp(Map map) throws Exception {
        if(map.get("id") != null && "".equals(map.get("id").toString())){
            return super.selectp(map);
        }

        List<Address> addressList = addressDao.query(map);
        if(addressList.size() == 0){
            return this.codeMess(eCode,"还有任何地址信息");
        }
        for(Address address : addressList){
            if(String.valueOf(IsDefault.是).equals(address.getIsDefault())){
                return this.codeData(address);
            }
        }
        return this.codeData(addressList.get(0));
    }

    private void setAllToUnDefault(Map map) throws Exception{
        Map addressMap = new HashMap();
        addressMap.put("openId",map.get("openId"));
        addressMap.put("isDefault", String.valueOf(IsDefault.否));
        addressDao.updatep(addressMap);
    }
}
